<template>
  <div class="online-user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>在线用户</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="user_agent" label="设备信息" show-overflow-tooltip />
        <el-table-column prop="login_at" label="登录时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.login_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="last_activity_at" label="最后活动时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.last_activity_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="formatted_online_duration" label="在线时长" width="120" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-permission="'online_users.assign'"
              type="warning"
              link
              @click="handleForceLogout(row)"
            >
              强制登出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current_page"
          v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/date'

const loading = ref(false)
const tableData = ref([])

const searchForm = reactive({
  username: '',
})

const pagination = reactive({
  current_page: 1,
  page_size: 15,
  total: 0,
})

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current_page,
      page_size: pagination.page_size,
      ...searchForm,
    }
    const response = await request.get('/online-users', { params })
    if (response.code === 200) {
      tableData.value = response.data.data
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取在线用户失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current_page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
  })
  handleSearch()
}

// 分页
const handleSizeChange = (size) => {
  pagination.page_size = size
  fetchData()
}

const handlePageChange = (page) => {
  pagination.current_page = page
  fetchData()
}

const handleForceLogout = async (row) => {
  try {
    await ElMessageBox.confirm('确定要强制登出该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.post(`/online-users/${row.id}/force-logout`)
    if (response.code === 200) {
      ElMessage.success('强制登出成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('强制登出失败:', error)
    }
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.online-user-container {
  // padding 由 app-container 统一管理

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

